//
//  NickViewController.m
//  HTHappySale
//
//  Created by 创维海通 on 2017/9/25.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "NickViewController.h"

//Request
#import "HTTPPromise+Me.h"

//Tools
#import "AppUtil.h"

@interface NickViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    NSString *nameTextParam;
    NSString *nameValue;
}
@property (strong, nonatomic) IBOutlet UITableView *NickTableView;

@end

@implementation NickViewController

- (instancetype)init:(NSString *)nameString
{
    if (self = [super init]) {
        nameTextParam = nameString;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initTableView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addNavigationLeftView:@"" andType:0];
    [self addNavigationMiddleView:@"昵称"];
    [self addNavigationRightView:@"保存"];
}

- (void)initTableView
{
    _NickTableView.tableFooterView = [[UIView alloc] init];
    _NickTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _NickTableView.scrollEnabled = NO;
    _NickTableView.backgroundColor = HTCFQuickRGBColor(247, 247, 247);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -tableDelegae

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

#define cellIdentify @"cell"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
    }
    
    //干掉contentView上面的子控件!! 节约内存!!
    for (NSInteger i = 1; i <= 5; i++) {
        //干掉contentView 上面的所有子控件!!
        [[cell.contentView viewWithTag:i] removeFromSuperview];
    }
    
    [[cell viewWithTag:500] removeFromSuperview];
    
    UITextField *nameText = [[UITextField alloc] initWithFrame:CGRectMake(20, 9.5, SCREEN_WIDTH - 40, 25)];
    nameText.delegate = self;
    nameText.clearButtonMode = UITextFieldViewModeWhileEditing;
    nameText.text = nameTextParam;
    nameText.tag = indexPath.row + 500;
    nameText.placeholder = @"请输入昵称";
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [nameText addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    
    [cell addSubview:nameText];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section{
    return 10;
}

#pragma mark -textFieldDelegate
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [[self view] endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark -Action
- (void)rightTapAction
{
    if(!HTCFVerifyNickName(nameValue)){
        [AppUtil showTipMessage:@"请输入正确的昵称"];
        return ;
    }
    NSDictionary *nickParam = @{@"nickname":nameValue};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:nickParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:nickParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    __weak __typeof(self)weakSelf = self;
    [HTTPPromise requestUserNicknameParams:jsonData Success:^(id responseObj) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"%@",responseObj);
        int successRet =[responseObj[@"ret"] intValue];
        //(数据转模型）
        if (successRet == 0) {
            [strongSelf skipController];
        }else{
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error.userInfo);
    }];
}

- (void)skipController
{
    if(!HTCFUDFEmptyValue(kNickNameKey))
    {
        HTCFUDFCache(kNickNameKey,nameValue);
        nickname =  HTCFUDFGetValue(kNickNameKey);
        NSLog(@"-------%@",nickname);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)textFieldWithText:(UITextField *)textField
{
    switch (textField.tag) {
        case 500:
            NSLog(@"%@",textField.text);
            nameValue = textField.text;
            break;
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField.tag == 500) {
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        //so easy
        else if (textField.text.length >= 15) {
            textField.text = [textField.text substringToIndex:15];
            return NO;
        }
    }
    return YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
